package com.cxs.utils;

import com.alibaba.druid.pool.DruidDataSourceFactory;

import javax.sql.DataSource;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Properties;

/**
 * @Project: jdbc
 * @Author: cxs2014501@163.com
 * @Create: 2022/8/30 17:20
 * @Description:
 **/
public class DbUtil {
    private static DataSource dataSource;

    static {
        Properties properties = new Properties();
        try {
            //加载注册驱动
            Class.forName("com.mysql.jdbc.Driver");
            InputStream in = FileReadUtil.getFileAsStream("db.properties");
            if (null == in) {
                throw new RuntimeException("db.properties文件未找到");
            }
            properties.load(in);
            dataSource = DruidDataSourceFactory.createDataSource(properties);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //创建连接对象
    public static Connection getConnection(){
        try {
            //获取连接对象
            return dataSource.getConnection();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    //关闭资源
    public static void close(Connection coll, PreparedStatement statement, ResultSet resultSet){
        try {
            if(coll!=null)
            {
                coll.close();
            }
            if(statement!=null)
            {
                statement.close();
            }
            if(resultSet!=null)
            {
                resultSet.close();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

}
